import { ref, computed } from "vue";
import { energyAppApi } from "@/api/business";
import dayjs from "dayjs";

export interface QueryData {
  hemsId?: number;
  beginDate?: string;
  endDate?: string;
  zone?: string;
  type: number; // 0:realtime 1:day 2:week 3:month 4:year 5:lifetime
  pvCircuit?: string;
  deviceId?: string;
}

export interface EnergyTotals {
  solarTotal: number;
  solarToHome: number;
  solarToStorage: number;
  homeTotal: number;
  homeFromSolar: number;
  homeFromStorage: number;
  homeFromGrid: number;
  batGridOutput: number;
  batGridInput: number;
  batToHome: number;
  batFromStorage: number;
  batFromGrid: number;
  gridToGrid: number;
  gridFromGrid: number;
}

export interface ProcessedData {
  solarList: number[];
  batteryList: number[];
  input: number[];
  output: number[];
  conList: number[];
  socList: number[];
  grid1Input: number[];
  grid1Output: number[];
  timePoints: string[];
}

export function useEnergyData() {
  const isLoading = ref(false);
  const isNothing = ref(false);

  // Energy totals
  const energyTotals = ref<EnergyTotals>({
    solarTotal: 0,
    solarToHome: 0,
    solarToStorage: 0,
    homeTotal: 0,
    homeFromSolar: 0,
    homeFromStorage: 0,
    homeFromGrid: 0,
    batGridOutput: 0,
    batGridInput: 0,
    batToHome: 0,
    batFromStorage: 0,
    batFromGrid: 0,
    gridToGrid: 0,
    gridFromGrid: 0
  });

  // Processed chart data
  const processedData = ref<ProcessedData>({
    solarList: [],
    batteryList: [],
    socList: [],
    input: [],
    output: [],
    conList: [],
    grid1Input: [],
    grid1Output: [],
    timePoints: []
  });

  // 5分钟数据聚合函数
  const aggregate5MinData = (data: any[], currentType: number) => {
    if (currentType === 0 && data) {
      const result = [];
      const totalMinutes = Math.min(data.length, 24 * 60);

      for (let i = 0; i < totalMinutes; i += 5) {
        let slice = data.slice(i, i + 5);

        if (slice.length < 5) {
          continue;
        }

        const sum = slice.reduce((acc, cur) => acc + cur.data, 0);
        const avg = sum / 5;

        const minutes = i;
        const hours = Math.floor(minutes / 60);
        const finalMinutes = minutes % 60;

        const timeString = `${String(hours).padStart(2, "0")}:${String(finalMinutes).padStart(
          2,
          "0"
        )}`;

        result.push({ dateTime: timeString, data: avg });
      }
      result.splice(-1);
      console.log(result);
      return result;
    }
    return data;
  };

  // 格式化数组数据
  const formatterArrayData = (
    data: any[],
    type1: number,
    type2?: number,
    currentType: number = 0
  ) => {
    let arr: number[][] = [];

    if (type2) {
      for (let i = 0; i < data.length; i += 1) {
        // 确保下标
        const data1 = aggregate5MinData(data[i].data[type1], currentType) || [];
        const data5 = aggregate5MinData(data[i].data[type2], currentType) || [];
        const combinedData = data1[0]?.dateTime
          ? data1.map((item, index) => item.data + (data5[index]?.data || 0))
          : data5.map((item) => item.data);
        arr.push(combinedData);
      }
    } else {
      for (let i = 0; i < data.length; i += 1) {
        // 确保下标
        const data1 = aggregate5MinData(data[i].data[type1], currentType) || [];
        arr.push(data1.map((item) => item.data));
      }
    }
    // 找到最大的数组长度
    const maxLength = Math.max(...arr.map((arr) => arr.length));

    // 使用 reduce 来计算每个下标的和
    const summedArray = Array.from({ length: maxLength }, (_, index) => {
      return arr.reduce((sum, currentArray) => {
        return sum + (currentArray[index] || 0);
      }, 0);
    });
    return summedArray;
  };

  // 格式化时间数据
  const formatterDate = (data: any[], currentType: number) => {
    console.log("formatterDate 输入数据:", data, "类型:", currentType);
    let date: string[] = [];

    switch (currentType) {
      case 0:
        date = data.map((item: any) => item.dateTime);
        break;
      case 1:
        break;
      case 2:
        // 周数据处理：调整周日到最前面
        const weekDays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; // 默认周日在最前
        date = data.map((item: any) => {
          return weekDays[dayjs(item.dateTime).day()];
        });
        break;
      case 3:
        // 月数据处理：只显示日期
        date = data.map((item: any) => item.dateTime.split("-")[2]);
        break;
      case 4:
        // 年数据处理：创建01到12的月份数组
        const allMonths = Array.from({ length: 12 }, (_, i) => String(i + 1).padStart(2, "0"));
        date = allMonths;
        break;
      default:
        date = data.map((item: any) => item.dateTime);
        break;
    }

    console.log("formatterDate 输出结果:", date);
    return date;
  };

  // 重置数据
  const resetData = () => {
    // 清空缓存
    allData = [];

    energyTotals.value = {
      solarTotal: 0,
      solarToHome: 0,
      solarToStorage: 0,
      homeTotal: 0,
      homeFromSolar: 0,
      homeFromStorage: 0,
      homeFromGrid: 0,
      batGridOutput: 0,
      batGridInput: 0,
      batToHome: 0,
      batFromStorage: 0,
      batFromGrid: 0,
      gridToGrid: 0,
      gridFromGrid: 0
    };

    processedData.value = {
      solarList: [],
      batteryList: [],
      input: [],
      output: [],
      conList: [],
      socList: [],
      grid1Input: [],
      grid1Output: [],
      timePoints: []
    };
  };

  // 缓存数据
  let allData: any[] = [];

  // 获取太阳能数据
  const getSolarFlowData = async (
    queryData: QueryData,
    currentSelect: number = 0,
    currentTimeType: number = 0
  ) => {
    isLoading.value = true;
    isNothing.value = false;

    try {
      // 有则先拿缓存
      let data: any[] = []; // 储能数据
      let ctData: any[] = [];

      if (allData.length > 0) {
        data = [allData[0]];
        if (allData.length > 1) {
          ctData = [allData[1]];
        }
      } else {
        const response = await energyAppApi.getSolarFlowAllList(queryData);
        data = response.data[0] ? [response.data[0]] : [];
        if (response.data.length > 1) {
          ctData = [response.data[1]];
        }
      }

      console.log("数据获取:", data, ctData, allData);

      const jsonData = data.filter((item: any) => JSON.stringify(item.data) !== "{}");
      if (jsonData.length === 0 && ctData.length === 0) {
        isNothing.value = true;
        resetData();
        return;
      }

      // 每次全部默认保存所有数据
      if (currentSelect === 0) {
        console.log("保存缓存数据", data, ctData);
        allData = [...data, ...ctData];
      } else {
        allData = [];
      }

      // 太阳能
      const solarTotal = data
        .map((item: any) => item.solar || 0)
        .reduce((accum: number, curr: number) => accum + curr, 0);
      // 离网输入
      const socketInputTotal = data
        .map((item: any) => item.socketInputTotal || 0)
        .reduce((accum: number, curr: number) => accum + curr, 0);
      // 离网光伏输入
      let ctGridInputTotal = 0;
      if (ctData.length > 0) {
        ctGridInputTotal = ctData
          .map((item: any) => item.gridInputTotal || 0)
          .reduce((accum: number, curr: number) => accum + curr, 0);
      }

      energyTotals.value.solarTotal = solarTotal + socketInputTotal + ctGridInputTotal; // 太阳能加上离网输入+屋顶光伏输入

      const batteryInput = data
        .map((item: any) => item.batteryOutput || 0)
        .reduce((accum: number, curr: number) => accum + curr, 0);
      const gridInputTotal = data
        .map((item: any) => item.gridInputTotal || 0)
        .reduce((accum: number, curr: number) => accum + curr, 0);
      const socketOutputTotal = data
        .map((item: any) => item.socketOutputTotal || 0)
        .reduce((accum: number, curr: number) => accum + curr, 0); // 12
      const gridDirectTotal = data
        .map((item: any) => item.gridDirectTotal || 0)
        .reduce((accum: number, curr: number) => accum + curr, 0); // 16

      energyTotals.value.solarToStorage =
        batteryInput - gridInputTotal < 0 ? 0 : batteryInput - gridInputTotal;
      energyTotals.value.solarToHome =
        energyTotals.value.solarTotal - energyTotals.value.solarToStorage < 0
          ? 0
          : energyTotals.value.solarTotal - energyTotals.value.solarToStorage;

      // 电池
      energyTotals.value.batToHome = data
        .map((item: any) => item.batteryInput || 0)
        .reduce((accum: number, curr: number) => accum + curr, 0);
      energyTotals.value.batFromGrid =
        data
          .map((item: any) => item.gridInputTotal || 0)
          .reduce((accum: number, curr: number) => accum + curr, 0) -
          socketOutputTotal <
        0
          ? 0
          : data
              .map((item: any) => item.gridInputTotal || 0)
              .reduce((accum: number, curr: number) => accum + curr, 0) - socketOutputTotal;
      energyTotals.value.batGridOutput = data
        .map((item: any) => item.batteryInput || 0)
        .reduce((accum: number, curr: number) => accum + curr, 0);
      energyTotals.value.batFromStorage =
        energyTotals.value.solarToStorage < 0 ? 0 : energyTotals.value.solarToStorage;
      energyTotals.value.batGridInput =
        energyTotals.value.batFromStorage + energyTotals.value.batFromGrid;

      // 家庭
      const homeTotal = data
        .map((item: any) => item.home || 0)
        .reduce((accum: number, curr: number) => accum + curr, 0); // 家庭总消耗+电网直通
      energyTotals.value.homeTotal = homeTotal + socketOutputTotal;
      energyTotals.value.homeFromSolar = energyTotals.value.solarToHome;
      const diff = energyTotals.value.homeFromSolar - energyTotals.value.homeTotal;
      energyTotals.value.homeTotal =
        diff > 0 ? energyTotals.value.homeTotal + diff : energyTotals.value.homeTotal;
      energyTotals.value.homeFromStorage = energyTotals.value.batGridOutput;

      // 太阳能1+5
      const solar1 = formatterArrayData(data, 1, 5, queryData.type);
      const solar2 = formatterArrayData(data, 14, 15, queryData.type);
      const socketInput = formatterArrayData(data, 13, undefined, queryData.type); // 离网输入总

      // 3相ct
      const ct1 = formatterArrayData(ctData, 12, 13, queryData.type);
      const ct2 = formatterArrayData(ctData, 14, 15, queryData.type);
      const ct3 = formatterArrayData(ctData, 16, 17, queryData.type);

      let ctTotals: number[];
      let solarTotals: number[];

      // 如果储能没数据 直接拿ct的
      if (jsonData.length === 0) {
        const ctLength = formatterArrayData(ctData, 1, undefined, queryData.type); // 为了取ct数组的长度 1是保证有数据
        ctTotals = ctLength.map(
          (item, index) => (ct1[index] || 0) + (ct2[index] || 0) + (ct3[index] || 0)
        );
        processedData.value.solarList = ctTotals;
      } else {
        // 新增三数组合并逻辑
        ctTotals = solar1.map(
          (item, index) => (ct1[index] || 0) + (ct2[index] || 0) + (ct3[index] || 0)
        );
        solarTotals = solar1.map((item, index) => item + (solar2[index] || 0));
        processedData.value.solarList = solarTotals.map(
          (item, index) => item + (socketInput[index] || 0) + (ctTotals[index] || 0)
        );
      }

      // Battery processing
      processedData.value.input = formatterArrayData(data, 2, 7, queryData.type); // 2+7
      const output = formatterArrayData(data, 4, 8, queryData.type); // 4 + 8
      processedData.value.output = output.map((item) => 0 - item);

      const arr: number[] = [];
      processedData.value.solarList.forEach((item, index) => {
        if (processedData.value.input[index] > 0) {
          if (processedData.value.input[index] > Math.abs(processedData.value.output[index] || 0)) {
            arr.push(processedData.value.input[index] || 0);
          } else {
            arr.push(processedData.value.output[index] || 0);
          }
        } else {
          arr.push(processedData.value.output[index] || 0);
        }
      });
      processedData.value.batteryList = arr;

      // Home processing
      const allList = formatterArrayData(data, 3, 12, queryData.type);
      const onGridList = formatterArrayData(data, 3, undefined, queryData.type);
      const offGridList = formatterArrayData(data, 12, undefined, queryData.type);
      processedData.value.conList = allList; // Default to all consumption

      // Time points
      let time = data.filter((item: any) => JSON.stringify(item.data) !== "{}");
      console.log("时间数据:", time);
      if (time.length === 0) {
        time = ctData.filter((item: any) => JSON.stringify(item.data) !== "{}");
      }

      if (time.length > 0) {
        const aggregatedData = aggregate5MinData(time[0].data[1], queryData.type);
        console.log("聚合前数据:", time[0].data[1]);
        console.log("聚合后数据:", aggregatedData);
        console.log("当前类型:", queryData.type);

        processedData.value.timePoints = formatterDate(aggregatedData, currentTimeType);

        console.log("最终时间点:", processedData.value.timePoints);
      }

      console.log("处理完成:", queryData.type, processedData.value.timePoints);
      isNothing.value = false;
    } catch (error) {
      console.error("Error fetching solar flow data:", error);
      isNothing.value = true;
    } finally {
      isLoading.value = false;
    }
  };

  // 获取电池数据
  const getBatteryData = async (queryData: QueryData, currentTimeType: number = 0) => {
    try {
      const response = await energyAppApi.getSolarFlowHemsElectricList(queryData);
      const data = response.data;

      const jsonData = data.filter((item: any) => JSON.stringify(item.energyVos) !== "[]");
      if (jsonData.length === 0) {
        return { socData: [], timePoints: [] };
      }

      const inputList: number[][] = [];
      for (let i = 0; i < data.length; i += 1) {
        const data1 = aggregate5MinData(data[i].energyVos, queryData.type) || [];
        inputList.push(data1.map((item: any) => item.data));
      }

      const maxLength = Math.max(...inputList.map((inputList) => inputList.length));
      const summedArray = Array.from({ length: maxLength }, (_, index) => {
        return inputList.reduce((sum, currentArray) => {
          return Math.min(Math.floor(sum + (currentArray[index] || 0) / inputList.length), 100);
        }, 0);
      });

      const time = data.filter((item: any) => JSON.stringify(item.energyVos) !== "[]");
      const timePoints = formatterDate(
        aggregate5MinData(time[0].energyVos, queryData.type),
        currentTimeType
      );

      processedData.value.socList = summedArray;
      return { socData: summedArray, timePoints };
    } catch (error) {
      console.error("Error fetching battery data:", error);
      return { socData: [], timePoints: [] };
    }
  };

  // 获取电网数据
  const getGridData = async (queryData: QueryData, currentTimeType: number = 0) => {
    try {
      const response = await energyAppApi.getCtHemsList(queryData);
      const data = response.data;

      if (JSON.stringify(data) === "{}" || JSON.stringify(data.data) === "{}") {
        energyTotals.value.gridFromGrid = 0;
        energyTotals.value.gridToGrid = 0;
        return { gridInput: [], gridOutput: [], timePoints: [] };
      }

      energyTotals.value.gridToGrid = data.gridReverseTotal;
      energyTotals.value.gridFromGrid = data.gridInputTotal;

      const timePoints = formatterDate(
        aggregate5MinData(data.data[1], queryData.type),
        currentTimeType
      );

      let grid1Input: number[];
      let grid1Output: number[];

      if (data.productType === 25) {
        grid1Input = aggregate5MinData(data.data[10], queryData.type).map((item: any) => item.data);
        grid1Output = aggregate5MinData(data.data[11], queryData.type).map(
          (item: any) => 0 - item.data
        );
      } else {
        const grid1InputData = aggregate5MinData(data.data[1], queryData.type).map(
          (item: any) => item.data
        );
        const grid2InputData = aggregate5MinData(data.data[3], queryData.type).map(
          (item: any) => item.data
        );
        const grid3InputData = aggregate5MinData(data.data[5], queryData.type).map(
          (item: any) => item.data
        );

        grid1Input = grid1InputData.map((value, index) => {
          return value + (grid2InputData[index] || 0) + (grid3InputData[index] || 0);
        });

        const grid1OutputData = aggregate5MinData(data.data[2], queryData.type).map(
          (item: any) => item.data
        );
        const grid2OutputData = aggregate5MinData(data.data[4], queryData.type).map(
          (item: any) => item.data
        );
        const grid3OutputData = aggregate5MinData(data.data[6], queryData.type).map(
          (item: any) => item.data
        );

        const array =
          [grid1OutputData, grid2OutputData, grid3OutputData].find((arr) =>
            queryData.type === 4 ? arr.length > 0 : arr.length > 1
          ) || [];

        grid1Output = array.map((value, index) => {
          return 0 - (value + (grid2OutputData[index] || 0) + (grid3OutputData[index] || 0));
        });
      }

      processedData.value.grid1Input = grid1Input;
      processedData.value.grid1Output = grid1Output;

      return { gridInput: grid1Input, gridOutput: grid1Output, timePoints };
    } catch (error) {
      console.error("Error fetching grid data:", error);
      return { gridInput: [], gridOutput: [], timePoints: [] };
    }
  };

  return {
    isLoading,
    isNothing,
    energyTotals: computed(() => energyTotals.value),
    processedData: computed(() => processedData.value),
    getSolarFlowData,
    getBatteryData,
    getGridData,
    resetData,
    aggregate5MinData,
    formatterArrayData,
    formatterDate
  };
}
